package com.customer.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.customer.dao.ClientMapper;
import com.customer.service.ClientService;
import com.nameless.entity.Client;
import com.nameless.entity.MemberLevel;
import com.nameless.util.JwtUtil;
import com.nameless.util.ValidateCodeUtils;
import com.nameless.util.WebUtils;
import com.nameless.vo.Result;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author WHZ
 * @date 2023年02月27日 22:11
 */
@RestController
@RequestMapping("/client/api")
public class ClientControllerApi {
    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiModelProperty(hidden = true)
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ClientService clientService;

    @Bean
    private PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @PostMapping("/selectId/{id}")
    public Client selectId(@PathVariable Integer id){
        Client client1 = clientMapper.selectById(id);
        return client1;
    }

    @PostMapping("/selectUsername/{name}")
    public Client selectName(@PathVariable String name){
        QueryWrapper<Client> wrapper = new QueryWrapper<>();
        wrapper.eq("username",name);
        Client client = clientMapper.selectOne(wrapper);
        return client;
    }

    @RequestMapping("/selectname/{username}")
    public Client getUsername(@PathVariable String username){
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Client::getUsername, username);
        return clientService.getOne(queryWrapper);
    }

    @RequestMapping("/info")
    public Result getInfo() {
        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = tokenChaim.get("clientname").toString();
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Client> eq = queryWrapper.eq(Client::getUsername, username);
        Client one = clientMapper.selectOne(eq);
        return new Result(200,"查询成功",one);
    }

    @RequestMapping("/put/{password}/{newpassword}")
    public Result upt(@PathVariable("password") String passwrord, @PathVariable("newpassword") String newpassword) {
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        String username = (String) tokenChaim.get("clientname");
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Client::getUsername,username);
        Client client = clientService.getOne(queryWrapper);
        if(passwrord!=null && newpassword!=null){
            if (passwordEncoder().matches(passwrord,client.getPassword())||passwrord.equals(client.getPassword())){
                client.setPassword(passwordEncoder().encode(newpassword));
                boolean b = clientService.updateById(client);
                return b?new Result(200,"修改成功"):new Result(500,"修改失败");
            }else {
                return new Result(500,"原密码错误");
            }
        }
        return new Result(500,"密码不能为空");
    }

    @RequestMapping("/register/{password}/{phoneNum}/{yz}")
    public Result register(@PathVariable("password") String password,@PathVariable("phoneNum") String phoneNum,@PathVariable("yz") String yz){
        String s = stringRedisTemplate.opsForValue().get(phoneNum);
        if (s.equals(yz)==true) {
        System.out.println(phoneNum);
        String regex = "^((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[56])|(17[0-8])|(18[0-9])|(19[1589]))\\d{8}$";
        Pattern  p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(phoneNum);
        boolean matches = matcher.matches();
        System.out.println(matches+"=======================");
        if (matches == true) {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                String encode = passwordEncoder.encode(password);
                Client allPone = clientMapper.getAllPone(phoneNum);
                if (allPone == null) {
                    Client client = new Client();
                    client.setPassword(encode);
                    client.setUsername(phoneNum);
                    client.setPhoneNum(phoneNum);
                    int insert = clientMapper.insert(client);
                    return new Result(200, "注册成功", insert);
                } else {
                    return new Result(500, "手机号已存在");
                }
            } else {
                return new Result(500, "手机号格式不正确");
            }
        }else {
            return new Result(500, "验证码不正确");
        }
    }

    @RequestMapping("/sendMsg/{phoneNum}")
    public Result<String> sendMsg (@PathVariable("phoneNum")String phoneNum) {
        Client allPone = clientMapper.getAllPone(phoneNum);
        if (allPone != null) {
            if (StringUtils.isNotEmpty(phoneNum)) {
                String code = ValidateCodeUtils.generateValidateCode(6).toString();
                stringRedisTemplate.opsForValue().set(phoneNum, code, 2, TimeUnit.MINUTES);
                return Result.success("手机验证码发送成功", code);
            }
        }
        return Result.error("手机号不存在");
    }

    @RequestMapping("/logout")
    public Result logout() {
        String token = WebUtils.getRequest().getHeader("token");
        System.out.println(token);
        redisTemplate.delete(token);
        return new Result(200,"退出成功");
    }

    @RequestMapping("/uppassword/{phoneNum}/{password}/{pin}")
    public Result uppassword (@PathVariable("phoneNum") String phoneNum, @PathVariable("password") String password, @PathVariable("pin") String pin) {
        String s = stringRedisTemplate.opsForValue().get(phoneNum);
        if (s.equals(pin)) {
            Client allPone = clientMapper.getAllPone(phoneNum);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(password);
            Integer id = allPone.getId();
            Integer uppassword = clientMapper.uppassword(encode, id);
            return new Result(200, "修改成功", uppassword);
        }else {
            return new Result(500,"验证码不正确");
        }

    }
}
